package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.*;
import com.leyou.seckill.client.SecKillClient;
import com.leyou.seckill.dto.SeckillPolicyDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    /**
     * 获取模板页面需要的商品数据
     * @param spuId
     * @return
     */
    public Map<String, Object> loadItemData(Long spuId) {

//        远程调用根据spuid  获取spu对象
        SpuDTO spuDTO = itemClient.findSpuById(spuId);
//        获取spu对应分类集合
        List<CategoryDTO> categoryDTOList = itemClient.findCategoryListByIds(spuDTO.getCategoryIds());
//      远程调用，根据品牌id查询品牌对象
        BrandDTO brandDTO = itemClient.findBrandById(spuDTO.getBrandId());
//        远程调用，根据spuid ，查询spuDetail信息
        SpuDetailDTO spuDetailDTO = itemClient.findSpuDetailBySpuId(spuId);
//        远程调用，根据spuid ，查询sku集合
        List<SkuDTO> skuDTOList = itemClient.findSkuListBySpuId(spuId);
//          远程调用，获取规格参数组和组内参数
        List<SpecGroupDTO> specGroupDTOList = itemClient.findSpecGroupByCid(spuDTO.getCid3());

        Map<String, Object> map = new HashMap<>();
        map.put("categories",categoryDTOList);
        map.put("brand",brandDTO);
        map.put("spuName",spuDTO.getName());
        map.put("subTitle",spuDTO.getSubTitle());
        map.put("detail",spuDetailDTO);
        map.put("skus",skuDTOList);
        map.put("specs",specGroupDTOList);
        return map;
    }

    String htmlPath = "C:\\workspace\\heima-jee-tj-2\\nginx-1.12.2\\html\\item";
    @Autowired
    private TemplateEngine templateEngine;
    /**
     * 生成静态页面
     */
    public void createHtml(Long spuId){
//        获取页面动态数据
        Map<String, Object> itemData = this.loadItemData(spuId);
//      创建上下文
        Context context = new Context();
//        把数据设置到上下文
        context.setVariables(itemData);
//      构造新的html存放的目录
        File dir = new File(htmlPath);
        if(!dir.exists()){
            dir.mkdir();
        }
//        创建新的html文件
        File newHtml = new File(dir,spuId+".html");
//        创建写文件的流
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(newHtml,"UTF-8");
            //        使用模板引擎生成页面
            templateEngine.process("item",context,writer);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }finally {
            if(writer!= null){
                writer.close();
            }
        }

    }

    /**
     * 删除静态页面
     * @param spuId
     */
    public void removeHtml(Long spuId) {
//      构造新的html存放的目录
        File dir = new File(htmlPath);
        if(dir.exists()){
            //html文件
            File newHtml = new File(dir,spuId+".html");
//            删除页面
            newHtml.delete();
        }

    }

    @Autowired
    private SecKillClient secKillClient;
    /**
     * 生成秒杀的列表页和详情页
     * @param date
     */
    public void createSecKillListAndDetailHtml(String date) {
//         远程调用seckill服务，根据date获取秒杀的列表
        List<SeckillPolicyDTO> seckillPolicyDTOList = secKillClient.findSecKillPolicyListByDate(date);
//        生成列表页
        createSecKillListHtml(seckillPolicyDTOList);
//        生成详情页
        for (SeckillPolicyDTO seckillPolicyDTO : seckillPolicyDTOList) {
            createDetailHtml(seckillPolicyDTO);
        }
    }



    private String secKillPagePath = "C:\\workspace\\heima-jee-tj-2\\nginx-1.12.2\\html\\seckill";
    /**
     * 生成秒杀列表页
     * @param seckillPolicyDTOList
     */
    private void createSecKillListHtml(List<SeckillPolicyDTO> seckillPolicyDTOList) {

//        创建上下文
        Context context = new Context();
//        把集合数据放入上下文
        context.setVariable("seckillList",seckillPolicyDTOList);
//      构造文件目录
        File dir = new File(secKillPagePath);
        if(!dir.exists()){
            dir.mkdir();
        }
        File listFile = new File(dir,"list.html");
        PrintWriter writer = null;
        try{
//        构造文件写入流
            writer = new PrintWriter(listFile,"UTF-8");
//        生成静态页面
            templateEngine.process("seckill-index",context,writer);
        }catch(Exception e){
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }finally {
            if(writer != null){
                writer.close();
            }
        }

    }

    /**
     * 生成详情页面
     * @param seckillPolicyDTO
     */
    private void createDetailHtml(SeckillPolicyDTO seckillPolicyDTO) {
//      spuID
        Long spuId = seckillPolicyDTO.getSpuId();
//        查询spu对应的detail数据
        SpuDetailDTO spuDetailDTO = itemClient.findSpuDetailBySpuId(spuId);
//        查询规格参数组和规格参数
        List<SpecGroupDTO> specGroupDTOList = itemClient.findSpecGroupByCid(seckillPolicyDTO.getCid3());
        //        创建上下文
        Context context = new Context();
//        把集合数据放入上下文
        context.setVariable("detail",spuDetailDTO);
        context.setVariable("seckillgoods",seckillPolicyDTO);
        context.setVariable("specs",specGroupDTOList);
//      构造文件目录
        File dir = new File(secKillPagePath);
        if(!dir.exists()){
            dir.mkdir();
        }
        File detailFile = new File(dir,seckillPolicyDTO.getId()+".html");
        PrintWriter writer = null;
        try{
//        构造文件写入流
            writer = new PrintWriter(detailFile,"UTF-8");
//        生成静态页面
            templateEngine.process("seckill-item",context,writer);
        }catch(Exception e){
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}
